<template>
  <el-dialog
    title="余额变更"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :destroy-on-close="true"
    width="650px"
    :close-on-click-modal="false">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      style="width: 100%"
      label-width="100px"
    >
      <el-form-item label="当前余额：" prop="second">
        <el-input placeholder="请输入内容" :value="balance" disabled>
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">增加</el-radio>
          <el-radio :label="2">减少</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="金额变更：" prop="change_balance">
        <el-input-number placeholder="请输入内容" v-model="form.change_balance" controls-position="right">
        </el-input-number><span style="margin-left: 10px">元</span>
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex;justify-content: center;">
      <el-button type="primary"
                 @click="cancel">取消
      </el-button>
      <el-button type="primary"
                 @click="submit">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { balanceChange } from '../api'

export default {
  name: 'balanceChange',
  data () {
    return {
      dialogVisible: false,
      form: {
        balance: '',
        type: 1,
        change_balance: ''
      },
      id: undefined,
      rule: {
        change_balance: [
          { required: true, message: '请输入变更金额' }
        ]
      }
    }
  },
  computed: {
    balance () {
      if (!this.form.balance && this.form.balance !== 0) {
        return this.form.change_balance
      }
      if (this.form.type === 1) {
        return this.form.balance + this.form.change_balance
      } else {
        return this.form.balance - this.form.change_balance
      }
    }
  },
  methods: {
    handleClose (done) {
      done()
    },
    open ({ id, balance }) {
      this.id = id
      this.form = { balance: balance / 100, type: 1, change_balance: '' }
      console.log(this.form)
      this.dialogVisible = true
      return new Promise((resolve) => {
        this._resolve = resolve
      })
    },
    cancel () {
      this.close()
    },
    close () {
      this._resolve({ refresh: true })
      this.dialogVisible = false
    },
    async submit () {
      await this.$refs.form.validate()
      const { change_balance, type } = this.form
      await balanceChange({ id: this.id }, { change_balance: change_balance * 100, type })
      this.$message.success('更新成功')
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
